package com.polidea.rxohosble2.internal.scan;


import com.polidea.rxohosble2.annotation.RestrictTo;
import bleshadow.javax.inject.Inject;
import com.polidea.rxohosble2.ClientScope;
import com.polidea.rxohosble2.internal.RxBleLog;
import com.polidea.rxohosble2.scan.ScanCallbackType;
import com.polidea.rxohosble2.scan.ScanRecord;
import com.polidea.rxohosble2.scan.ScanSettings;
import com.polidea.rxohosble2.internal.util.UUIDUtil;
import ohos.bluetooth.ble.BlePeripheralDevice;
import ohos.bluetooth.ble.BleScanResult;

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@ClientScope
public class InternalScanResultCreator {

    @SuppressWarnings("deprecation")
    private final UUIDUtil uuidUtil;

    @Inject
    @SuppressWarnings("deprecation")
    public InternalScanResultCreator(UUIDUtil uuidUtil) {
        this.uuidUtil = uuidUtil;
    }

    public RxBleInternalScanResult create(BlePeripheralDevice bluetoothDevice, int rssi, byte[] scanRecord) {
        final ScanRecord scanRecordObj = uuidUtil.parseFromBytes(scanRecord);
        return new RxBleInternalScanResult(bluetoothDevice, rssi, System.nanoTime(), scanRecordObj,
                ScanCallbackType.CALLBACK_TYPE_UNSPECIFIED);
    }

    public RxBleInternalScanResult create(BleScanResult result) {
        final ScanRecordImplNativeWrapper scanRecord = new ScanRecordImplNativeWrapper(result);
        return new RxBleInternalScanResult(result.getPeripheralDevice(), result.getRssi(), result.getTime(), scanRecord,
                ScanCallbackType.CALLBACK_TYPE_BATCH);
    }

    public RxBleInternalScanResult create(int callbackType, BleScanResult result) {
        final ScanRecordImplNativeWrapper scanRecord = new ScanRecordImplNativeWrapper(result);
        return new RxBleInternalScanResult(result.getPeripheralDevice(), result.getRssi(), result.getTime(), scanRecord,
                toScanCallbackType(callbackType));
    }

    private static ScanCallbackType toScanCallbackType(int callbackType) {
        switch (callbackType) {
            case ScanSettings.CALLBACK_TYPE_ALL_MATCHES:
                return ScanCallbackType.CALLBACK_TYPE_ALL_MATCHES;
            case ScanSettings.CALLBACK_TYPE_FIRST_MATCH:
                return ScanCallbackType.CALLBACK_TYPE_FIRST_MATCH;
            case ScanSettings.CALLBACK_TYPE_MATCH_LOST:
                return ScanCallbackType.CALLBACK_TYPE_MATCH_LOST;
            default:
                RxBleLog.w("Unknown callback type %d -> check ohos.bluetooth.le.ScanSettings", callbackType);
                return ScanCallbackType.CALLBACK_TYPE_UNKNOWN;
        }
    }
}
